package com.it.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.Properties;

@PropertySource(value = "classpath:jdbc.properties",encoding = "UTF-8")
//开启mybatis的接口扫描
@MapperScan("com.itheima.mapper")
public class MybatisConfig {

    @Value("${jdbc.driverClass}")
    private String className;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.userName}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 配置数据源
     * @return
     */
    @Bean("dataSource")
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(className);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }

    /**
     * 配置会话工厂bean
     * @param dataSource
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Autowired DataSource dataSource){
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        //注入数据源
        sessionFactoryBean.setDataSource(dataSource);
        //设置mybatis的运行时的行为
        org.apache.ibatis.session.Configuration configuration =new org.apache.ibatis.session.Configuration();
        //开启驼峰
        configuration.setMapUnderscoreToCamelCase(true);
        //配置sql日志打印
        configuration.setLogImpl(StdOutImpl.class);
        sessionFactoryBean.setConfiguration(configuration);
        //给pojo类扫包取别名
        sessionFactoryBean.setTypeAliasesPackage("com.itheima.pojo");
        //配置插件
        PageInterceptor pi = new PageInterceptor();
        Properties props=new Properties();
        props.setProperty("helperDialect","mysql");
        props.setProperty("reasonable","true");
        pi.setProperties(props);
        Interceptor[] interceptors =new Interceptor[]{pi};
        sessionFactoryBean.setPlugins(interceptors);
        return sessionFactoryBean;
    }


}
